package com.xiaoyuzhou.logic;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.xiaoyuzhou.untity.AddressData;
import com.xiaoyuzhou.untity.Weather;
import com.xiaoyuzhou.untity.WeatherHeap;
import com.xiaoyuzhou.utils.CalendarUtils;

public class XmlParser {
	/**
	 * 解析位置信息
	 * Description:
	 * @param is
	 * @return
	 * @throws Exception
	 *<br/> ModifiedLog:
	 *<br/> Log ID: 1.0 (Log编号 依次递增)
	 * <br/>Modified By: liubin Email:liubin@d-heaven.com at 2012-11-7 下午05:09:46
	 */
	public static AddressData parseAddressData(InputStream is) throws Exception {
		AddressData address = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int event = parser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				address = new AddressData();
				break;
			case XmlPullParser.START_TAG:
				if(address != null) {
					if ("formatted_address".equals(parser.getName())) {
						address.setFormatted_address(parser.nextText());
					} else if ("lat".equals(parser.getName())) {
						address.setLat(Double.valueOf(parser.nextText()));
					} else if ("lng".equals(parser.getName())) {
						address.setLng(Double.valueOf(parser.nextText()));
					} else if ("district".equals(parser.getName())) {
						address.setDistrict(parser.nextText());
					} else if ("city".equals(parser.getName())) {
						address.setCity(parser.nextText());
					} else if ("province".equals(parser.getName())) {
						address.setProvince(parser.nextText());
					}
				}
				break;
			case XmlPullParser.END_TAG:
				break;
			default:
				break;
			}
			event = parser.next();
		}
		return address;
	}
	
	public static Map<String, String> parseProvince(InputStream is) throws Exception {
		Map<String, String> provinces = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int event = parser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				provinces = new HashMap<String, String>();
				break;
			case XmlPullParser.START_TAG:
				if(parser.getName().equals("string")) {
					String value = parser.nextText();
					String s[] = value.split(";");
					provinces.put(s[0], s[1]);
				} 
				break;
			default:
				break;
			}
			event = parser.next();
		}
		return provinces;
	}
	
	public static Map<String, String> parseCityDateSet(InputStream is) throws Exception {
		Map<String, String> cities = null;
		String cityID = "";
		String cityName = "";
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int event = parser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				break;
			case XmlPullParser.START_TAG:
				if(parser.getName().equals("Region")) {
					cities = new HashMap<String, String>();
				} else if(parser.getName().equals("CityID")) {
					cityID = parser.nextText();
				} else if(parser.getName().equals("CityName")) {
					cityName = parser.nextText();
				}
				break;
			case XmlPullParser.END_TAG:
				if(parser.getName().equals("City")) {
					cities.put(cityName, cityID);
				}
				if(parser.getName().equals("DataSet")){
					return cities;
				}
				break;
			default:
				break;
			}
			event = parser.next();
		}
		return cities;
	}
	
	public static WeatherHeap parseWeatherHeap(InputStream is, String cityCode) throws Exception {
		WeatherHeap weather = null;
		Weather forecast = null;//天气预报，用来存入weather.forecast集合
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int event = parser.getEventType();
		int index = 0;//string标签的序号，从0开始
		
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				break;
			case XmlPullParser.START_TAG:
				if (parser.getName().equals("ArrayOfString")) {
					weather = new WeatherHeap();
					weather.setDate(CalendarUtils.getMonthDate());
				} else if (parser.getName().equals("string")) {
					if (weather != null) {
						String value = parser.nextText();
						switch (index) {
						case 0:// Array(0) = "省份 地区/洲 国家名（国外）"
							if (value.startsWith("查询结果为空") || value.startsWith("发现错误")) {
								return null;
							}
							weather.setProvince(value.substring(0, value.indexOf(" ")));
							weather.setCity(value.substring(value.indexOf(" ")));
							break;
						case 1:// Array(1) = "查询的天气预报地区名称"
							weather.setDistrict(value);
							break;
						case 2:// Array(2) = "查询的天气预报地区ID"
							weather.setCityCode(value);
							break;
						case 3:// Array(3) = "最后更新时间 格式：yyyy-MM-dd HH:mm:ss"
							weather.setUpdateTime(value);
							break;
						case 4:// Array(4) = "当前天气实况：气温、风向/风力、湿度"
							String s[] = value.substring(7).split("；");
							String currentTemperature = s[0].split("：")[1];
							String currentWind = s[1].split("：")[1];
							String currentHumidity = s[2].split("：")[1];
							weather.setCurrentTemperature(currentTemperature);
							weather.setCurrentWind(currentWind);
							weather.setCurrentHumidity(currentHumidity);
							break;
						case 5:// Array(5) = "第一天 空气质量、紫外线强度"
							String s1[] = value.split("；");
							String airQuality = s1[0].substring(s1[0]
									.indexOf("空气质量："));
							String ziwaixian = s1[1].substring(s1[1]
									.indexOf("紫外线强度："));
							weather.setAirQuality(airQuality);
							weather.setZiwaixian(ziwaixian);
							break;
						case 6:// Array(6) = "第一天 天气和生活指数"
							weather.setLifeSuggestion(value);
							break;
						default:
							switch ((index - 7) % 5) {
							case 0:// Array(n-4) = "第二天 概况 格式：M月d日 天气概况"
								forecast = weather.newForecast();
								String s4[] = value.split(" ");
								forecast.setDate(s4[0]);
								forecast.setWeatherDetail(s4[1]);
								break;
							case 1:// Array(n-3) = "第二天 气温"
								forecast.setTemperature(value);
								break;
							case 2:// Array(n-2) = "第二天 风力/风向"
								forecast.setWind(value.replace("无持续风向", ""));
								break;
							case 3:// Array(n-1) = "第二天 天气图标 1"
								forecast.setWeatherIcon1(value);
								break;
							case 4:// Array(n) = "第二天 天气图标 2"
								forecast.setWeatherIcon2(value);
								weather.getForecast().add(forecast);
								forecast = null;
								break;
							default:
								break;
							}
							break;
						}
						index++;
					}
				}
				break;
			case XmlPullParser.END_TAG:
				break;
			default:
				break;
			}
			event = parser.next();
		}
		System.out.println(weather.toString());
		return weather;
	}
	
	public static Weather parseWeather(InputStream is, String date) throws Exception {
		Weather weather = null;
		String location = "";
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int event = parser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				break;
			case XmlPullParser.START_TAG:
				if (parser.getName().equals(Weather.DB_CITY)) {
					location = parser.nextText();
				} else if (parser.getName().equals(Weather.DB_FORECAST)) {
					if(date.equals(parser.getAttributeValue(null, Weather.DB_DATE))) {
						weather = new Weather();
						weather.setDate(date);
						weather.setLocation(location);
					}
				} else if(weather != null) {
					if (parser.getName().equals(Weather.DB_TEMPERATURE)) {
						weather.setTemperature(parser.nextText());
					} else if (parser.getName().equals(Weather.DB_WIND)) {
						weather.setWind(parser.nextText());
					} else if (parser.getName().equals(Weather.DB_WEATHER_DETAIL)) {
						weather.setWeatherDetail(parser.nextText());
					} 
				}
				break;
			case XmlPullParser.END_TAG:
				if (parser.getName().equals(Weather.DB_FORECAST)) {
					//已经获取到需要的那一天的天气，不需要再继续解析了
					if(weather != null && weather.getDate() != null && !weather.getDate().equals("")) {
						return weather;
					}
				}
				break;
			default:
				break;
			}
			event = parser.next();
		}
		return null;
	}
	
	/**
	 * 以标准xml保存天气数据，保存至data目录，文件名为citycode
	 * Description:
	 * @param weatherHeap
	 * @return
	 * @throws Exception
	 */
	public static void serializeWeather(WeatherHeap weatherHeap, OutputStream os) throws Exception {
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(os, "UTF-8");
		
	//	<WeatherHeap>
	//		<City>北京海淀区</City>
	//		<CityCode>222</CityCode>
	//		<Forecast date="">
	//			<Temperature></Temperature>
	//			<Wind></Wind>
	//			<WeatherDetail></WeatherDetail>
	//		</Forecast>
	//		<Forecast date="">
	//			...
	//		</Forecast>
	//	</WeatherHeap>
		
		String nameSpace = null;
		
		serializer.startDocument("UTF-8", true);
		serializer.startTag(nameSpace, Weather.DB_WEATHERHEAP);//<WeatherHeap>
		serializer.startTag(nameSpace, Weather.DB_CITY);//<City>
		serializer.text(weatherHeap.getLocation());
		serializer.endTag(nameSpace, Weather.DB_CITY);//</City>
		serializer.startTag(nameSpace, Weather.DB_CITYCODE);//<CityCode>
		serializer.text(weatherHeap.getCityCode());
		serializer.endTag(nameSpace, Weather.DB_CITYCODE);//</CityCode>
		for (Weather forecast:weatherHeap.getForecast()) {//遍历保存预报
			serializer.startTag(nameSpace, Weather.DB_FORECAST);//<Forecast>
			serializer.attribute(nameSpace, Weather.DB_DATE, forecast.getDate());//<Forecast date="">
			serializer.startTag(nameSpace, Weather.DB_TEMPERATURE);//<Temperature>
			serializer.text(forecast.getTemperature());
			serializer.endTag(nameSpace, Weather.DB_TEMPERATURE);//</Temperature>
			serializer.startTag(nameSpace, Weather.DB_WIND);//<Wind>
			serializer.text(forecast.getWind());
			serializer.endTag(nameSpace, Weather.DB_WIND);//</Wind>
			serializer.startTag(nameSpace, Weather.DB_WEATHER_DETAIL);//<WeatherDetail>
			serializer.text(forecast.getWeatherDetail());
			serializer.endTag(nameSpace, Weather.DB_WEATHER_DETAIL);//</WeatherDetail>
			serializer.endTag(nameSpace, Weather.DB_FORECAST);//</Forecast>
		}
		
		serializer.endTag(nameSpace, Weather.DB_WEATHERHEAP);//</WeatherHeap>
		serializer.endDocument();
	}
	
}
